﻿using System.Windows.Input;
using StockModel;
using Utils;
using Utils.Wpf;

namespace Plugins.UserControls
{
    public class StockSelectorVM : ViewModelBase
    {
        #region Attributes

        private readonly RawStockDataSource _rawStockDataSource;

        #endregion

        #region Properties

        public StockSelectorData Data { get; private set; }

        public string SelectedStockName
        {
            get
            {
                return this.Data.SelectedStockName;
            }
            set
            {
                if (this.Data.SelectedStockName != value)
                {
                    this.Data.SelectedStockName = value;
					base.OnPropertyChanged("SelectedStockName");
                    base.OnPropertyChanged("IsStockSelected");
                }
            }
        }

        public bool IsStockSelected
        {
            get
            {
                return !string.IsNullOrEmpty(this.Data.SelectedStockName);
            }
        }

        public ObservableCollection2<string> StockNames { get; private set; }
        public ICommand RefreshStocksAvailable { get; private set; }
        
        #endregion

        #region Public Methods

        public StockSelectorVM(RawStockDataSource rawStockDataSource)
        {
            _rawStockDataSource = rawStockDataSource;

            this.StockNames = new ObservableCollection2<string>();
            this.RefreshStocksAvailable = new DelegateCommand(ExecuteRefreshStocksAvailable, CanRefreshStocksAvailable);
            this.Data = new StockSelectorData();
			this.Data.PropertyChanged += Data_PropertyChanged; // Local object
        }

        #endregion

		#region Event Handlers
		
		private void Data_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
		{
			if (e.PropertyName == "SelectedStockName")
			{
				base.OnPropertyChanged("IsStockSelected");
				if (this.RefreshStocksAvailable.CanExecute(null))
				{
					this.RefreshStocksAvailable.Execute(null);	
				}
			}

			base.OnPropertyChanged(e.PropertyName);
		}

		#endregion

		#region Private Methods

		private void ExecuteRefreshStocksAvailable()
        {
            this.StockNames.Clear();

            foreach (string stockName in _rawStockDataSource.GetStockNames())
            {
                this.StockNames.Add(stockName);
            }
        }

        private bool CanRefreshStocksAvailable()
        {
            return this.StockNames.Count == 0;
        }

        #endregion
    }
}
